/*
 * @lc app=leetcode.cn id=24 lang=golang
 *
 * [24] 两两交换链表中的节点
 */

// 2-2. 迭代
// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	var dummyHead = &ListNode{0, head}
	var root = dummyHead
	for root != nil && root.Next != nil && root.Next.Next != nil {
		n1 := root.Next
		n2 := n1.Next

		n1.Next = n2.Next
		n2.Next = n1

		root.Next = n2
		root = n1
	}

	return dummyHead.Next
}

// @lc code=end

// 2-1. 迭代
// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	dummyHead := &ListNode{0, head}
	pre := dummyHead
	for head != nil {
		if head.Next == nil {
			pre.Next = head
			return dummyHead.Next
		}
		next := head.Next
		head.Next = nil
		nn := next.Next

		next.Next = head
		pre.Next = next
		pre = head

		head = nn
	}

	return dummyHead.Next
}

// @lc code=end

// 1. 递归
// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	next := head.Next
	nn := next.Next

	next.Next = head
	head.Next = swapPairs(nn)
	return next
}

// @lc code=end

